package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //获取手机号
        String phone = user.getPhone();

        //生成四位验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();

        //调用阿里的工具类去发送短信
        //SMSUtils.sendMessage("黑马旅游网","SMS_205126318",phone,code);
        log.info("=========本次验证码为=========" + code);

//        session.setAttribute(phone,code);
        redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);

        return R.success("发送成功");

    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map<String, String> param, HttpSession session) {
        //取出参数
        String phone = param.get("phone");
        String code = param.get("code");
//        String codeInSession = (String) session.getAttribute(phone);
        String codeInRedis = (String) redisTemplate.opsForValue().get(phone);

        //把参数交给Service，返回当前登录者
        User user = userService.login(phone, code, codeInRedis);
        if (user != null){
            session.setAttribute("user",user.getId());
            redisTemplate.delete(phone);
        }else {
            return R.error("登陆失败");
        }
        return R.success(user);

    }

    @PostMapping("/loginout")
    public R<String> loginout(HttpSession session){
        session.invalidate();
        return R.success("退出成功");
    }


}
